import { Component, OnInit, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { SFComponent, SFSchema, SFSelectWidgetSchema, SFUISchema, SFUploadWidgetSchema } from '@delon/form';
import { ModalHelper, _HttpClient } from '@delon/theme';
import { Observable, Observer } from 'rxjs';
import { AccountService } from '../../services/account.service';
import { AccountComponentsEditNameComponent } from '../edit-name/edit-name.component';
import { NzModalService } from 'ng-zorro-antd/modal';
import { AccountComponentsCenterEditComponent } from '../edit-password/edit-password.component';

@Component({
  selector: 'app-account-components-center',
  templateUrl: './center.component.html',
  styleUrls: ['./center.component.less'],
})
export class AccountComponentsCenterComponent implements OnInit {
  url = `/rule?_allow_anonymous=true`;
  @ViewChild('sf', { static: false }) sf!: SFComponent;
  i: any;
  formDate: any = {};
  schema!: SFSchema;
  ui: SFUISchema = {};
  infoData: any = {
    appId: '',
    appTypeId: 0,
    appTypeName: '',
    appUserId: 0,
    avatar: 'https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png?_allow_anonymous=true',
    birthday: '',
    cert: 0,
    createTime: '',
    email: '',
    id: 0,
    isPwd: true,
    lastLoginDate: '',
    name: '',
    nickName: '',
    openId: '',
    phone: '',
    remark: '',
    sex: 0,
    state: 0,
    stateLocked: true,
    token: '',
    userType: 0,
  };
  tabs = [
    {
      name: '基本设置',
    },
    {
      name: '安全设置',
    },
  ];
  idx: any = 0;
  defaultCompany: any = {};
  ifHasPayPw = false;
  constructor(public service: AccountService, private modal: ModalHelper, private http: _HttpClient, private router: Router, private modalService: NzModalService,) {}

  ngOnInit() {
    this.initSF();
    this.getInfo();
  }
  initSF() {
    this.schema = {
      properties: {
        avatar: {
          type: 'string',
          title: '头像',
          ui: {
            action: `/cms/upload/multipartFile/fileModel?_allow_anonymous=true`,
            fileType: 'image/png,image/jpeg,image/jpg,image/png,image/gif,image/bmp',
            limit: 1,
            limitFileCount: 1,
            resReName: 'url',
            urlReName: 'url',
            widget: 'upload',
            descriptionI18n: '支持JPG、GIF、PNG、JPEG、BMP格式，文件小于2M',
            data: {
              // appId: environment.appId,
            },
            name: 'multipartFile',
            multiple: false,
            listType: 'picture-card',
            change: (args: any) => {
              if (args.type === 'success') {
                const avatar = [
                  {
                    uid: -1,
                    name: 'LOGO',
                    status: 'done',
                    url: args.fileList[0].response.url,
                    response: {
                      url: args.fileList[0].response.url,
                    },
                  },
                ];
                this.sf?.setValue('/avatar', avatar);
              }
            },
            beforeUpload: (file: any, _fileList) => {
              return new Observable((observer: Observer<boolean>) => {
                const isLt2M = file.size / 1024 / 1024 < 2;
                if (!isLt2M) {
                  this.service.msgSrv.warning('图片大小超过2M!');
                  observer.complete();
                  return;
                }
                observer.next(isLt2M);
                observer.complete();
              });
            },
          } as SFUploadWidgetSchema,
        },
        nickName: {
          title: '昵称',
          type: 'string',
          minLength: 1,
          maxLength: 18,
          ui: {
            placeholder: '请输入昵称',
            width: 400,
            errors: {
              required: '请输入昵称',
            },
          },
        },
      },
      required: ['nickName', 'avatar'],
    };
    this.ui = {
      '*': {
        spanLabel: 5,
        grid: { span: 24 },
      },
    };
  }
  getInfo() {
    this.service.http.post(this.service.$api_get_current_user_info).subscribe((res) => {
      this.infoData = res.data;
      // this.getDeafaultCompany();
      this.getPayPw();
    });
  }

  getDeafaultCompany() {
    this.service.request(this.service.$api_getUserDefaultEnterpriseProject).subscribe(res => {
      if (res === null) {
        this.router.navigate(['/changeproject']);
        return;
      }
      this.defaultCompany = res
      if (res.projectId) {
        this.getPayPw()                   
      }
    })
  }

  getPayPw() {
    this.service.request(this.service.$api_isUserVerifyPassword, {}).subscribe(res => {
      this.ifHasPayPw = res
    })
  }

  

  edit(tpye: string) {
    if (tpye === 'phone') {
      const modalRef = this.modalService.create({
        nzTitle: '验证手机号码',
        nzContent: AccountComponentsEditNameComponent,
        nzComponentParams: {
          i: this.infoData
         },
         nzFooter: null
      });
      modalRef.afterClose.subscribe((result: any) => {
        if (result === true) {
          // this.st.load(1);
        }
      });
    }
    if (tpye === 'password') {

    const modalRef = this.modalService.create({
      nzTitle: '设置/修改登录密码',
      nzContent: AccountComponentsCenterEditComponent,
      nzComponentParams: {
        record: this.infoData
       },
    });
    modalRef.afterClose.subscribe((result: any) => {
      if (result === true) {
        // this.st.load(1);
      }
    });
    }

    if (tpye === 'payPassword') {
      this.router.navigate(['/account/edit-paypassword']);
    }
    // if (tpye === 'info') {
    //   this.router.navigate(['/account/editInfo'], {
    //     queryParams: { realName: this.infoData.realName, certificateNumber: this.infoData.certificateNumber },
    //   });
    // }
    // if (tpye === 'name') {
    //   this.modal
    //     .createStatic(AccountComponentsEditNameComponent, { i: { name: this.infoData.name, phone: this.infoData.phone } })
    //     .subscribe(() => {
    //       this.getInfo();
    //       // this.st.reload();
    //     });
    // }
  }

  changeType(type: number): void {
    this.idx = type;
  }

  formSubmit(value: any): void {
    const params = { ...value };
    this.service.request(`${this.service.$api_get_current_user_info}`, params).subscribe((res) => {
      if (res === true) {
        this.service.msgSrv.success('保存成功');
        this.getInfo();
        // this.initSF();
      }
    });
  }
}
